package ee.ut.maxorato_macobo.oop.mud.items;

import ee.ut.maxorato_macobo.oop.mud.game.GameRoom;

public class ItemLoader {
	static long nextLoaderIndex = 1;
	
	private ItemBase baseCopy;
	private ItemBase worldCopy;
	private long loaderIndex;
	private long lastDetach;
	private int repopTime;
	private GameRoom repopRoom;
	
	public ItemLoader(ItemBase newBaseCopy, int newRepopTime, GameRoom newRepopRoom) {
		loaderIndex = nextLoaderIndex++;
		
		repopRoom = newRepopRoom;
		baseCopy = newBaseCopy;
		worldCopy = null;
		
		lastDetach = 0;
		repopTime = newRepopTime;
		
		createInstanceNow();
	}
	
	public long getIndex() {
		return loaderIndex;
	}
	
	public void createInstanceNow() {
		if(worldCopy != null) return;
		
		worldCopy = baseCopy.clone();
		worldCopy.moveToLocation(repopRoom);
		worldCopy.attachLoader(this);
	}
	
	public ItemBase getWorldInstance() {
		return worldCopy;
	}
	
	public void processRepopping() {
		if(worldCopy == null && lastDetach + 1000000000L * repopTime < System.nanoTime()) {
			createInstanceNow();
		}
	}
	
	public void instanceDetached() {
		worldCopy = null;
		lastDetach = System.nanoTime();
	}

}
